package com.mf.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;


/**
 * @Author: lmf
 * @Create: 2024/5/14 21:37
 * Description:
 */
public class JsonParser {

    public static <T> T parseJsonToObject(Class<T> clazz, String jsonString,String dm) {
        // 使用Hutool的JSONObject解析JSON字符串
        JSONObject jsonObject = JSONUtil.parseObj(jsonString);
        T item = null;
        try {
            item = clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        // 遍历类的所有字段
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true); // 允许访问私有字段
            String fieldName = field.getName();

            // 检查JSON对象是否包含对应的键
            if (jsonObject.containsKey(fieldName)) {
                Object value = jsonObject.get(fieldName);

                // 检查字段类型并进行相应转换
                Class<?> fieldType = field.getType();
                if (BigDecimal.class.equals(fieldType)) {
                    // 如果是BigDecimal类型，确保value是字符串并转换为BigDecimal
                    if (value instanceof String) {
                        value = new BigDecimal((String) value);
                    } else {
                        throw new RuntimeException("Field " + fieldName + " of type BigDecimal expects a String value in JSON.");
                    }
                } else if (Integer.TYPE.equals(fieldType) || Integer.class.equals(fieldType)) {
                    // 如果是int或Integer类型，转换为Integer
                    if (value instanceof Number) {
                        value = ((Number) value).intValue();
                    } else if (value instanceof String) {
                        value = Integer.valueOf((String) value);
                    } else {
                        throw new RuntimeException("Field " + fieldName + " of type Integer expects a Number or String value in JSON.");
                    }
                }

                // 尝试设置字段值
                try {
                    setFieldValue(item, field, value);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        try {
            setFieldValue(item, item.getClass().getDeclaredField("id"), null);
            setFieldValue(item, item.getClass().getDeclaredField("dm"), dm);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }


        return item;
    }

    private static void setFieldValue(Object item, Field field, Object value) throws IllegalAccessException {
        field.setAccessible(true); // 确保可以访
        field.set(item, value);
    }
}
